//: [Previous](@previous)
/*:
 
 #14 [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/description/)
 
 最大公共前缀
 
 Write a function to find the longest common prefix string amongst an array of strings.
 
 If there is no common prefix, return an empty string "".
 
 Example 1:
 ```
 Input: ["flower","flow","flight"]
 Output: "fl"
 ```
 
 Example 2:
 ```
 Input: ["dog","racecar","car"]
 Output: ""
 Explanation: There is no common prefix among the input strings.
 ```
 
 **Note:**
 
 All given inputs are in lowercase letters a-z.
 
 */
import Foundation

class Solution {
    // 排序后比较1与最后一个
    func longestCommonPrefix(_ strs: [String]) -> String {
        if strs.count == 0 {
            return ""
        }
        if strs.count == 1 {
            return strs.first!
        }
        
        let sortStrs = strs.sorted()
        let s0 = sortStrs.first!
        let s1 = sortStrs.last!
        
        let count = min(s0.count, s1.count)
        var result = ""
        for i in 0..<count {
            if s0[i] != s1[i] {
                return result
            } else {
                result += String(s0[i])
            }
        }
        return result
    }
    
    
}

print(Solution().longestCommonPrefix(["flower","flow","flight"]))
print(Solution().longestCommonPrefix(["dog","racecar","car"]))
print(Solution().longestCommonPrefix(["c","c"]))


//: [Next](@next)
